
class UICounterItem < UIMenuItem
  COUNTER_TEXT_HEIGHT = 13
  attr_reader :action, :value

  def initialize(window, delegate, text, range)
    super(window, delegate, text)
    @action = action # symbol in the form of :method_name
    # action is called to delegate when the button is clicked.
    @button_image = window.images['../3d_renders/counter_item.png']
    @value = range[0]
    @range = range # range is an array with 2 items, lower & upper limit
    set_text_height(COUNTER_TEXT_HEIGHT)
  end

  def update(x, y, width, height, mouse_x, mouse_y)
    # calculate dimensions of background image before drawing.
    # also determine whether the mouse is hovering over valid content.
    super # sets @x, @y, @width, @height, and @color

    @value = @range[0] if @value < @range[0]
    @drawn_text = @text + ": #{@value}"
    border_x = width.to_f / 8
    border_y = height.to_f / 8
    @image_x, @image_y = @x + border_x, @y + border_y
    @image_w, @image_h = @width - 2*border_x, @height - 2*border_y
    return if @state == :disabled

    #ensure the button color stays normal unless mouse_over gets called.
    if mouse_x >= @image_x and mouse_x <= @image_x + @image_w and
      mouse_y >= @image_y and mouse_y <= @image_y + @image_h
        mouse_over
    else
      @state = :static
    end
  end

  def draw
    @button_image.draw_as_quad(@image_x, @image_y, @color,
                        @image_x + @image_w, @image_y, @color,
                        @image_x + @image_w, @image_y + @image_h, @color,
                        @image_x, @image_y + @image_h, @color,
                        ZOrder::BUTTON)
    @font.draw_rel(@drawn_text, @image_x + @image_w/2, @image_y + @image_h/2,
                   ZOrder::TEXT, 0.5, 0.5, 1, 1, @t_color)
  end

  def clicked(left_or_right, mx, my)
    return if @state != :hover
    case left_or_right
    when :left
      #@selected_sound.play
      if mx >= @image_x + @image_w/1.5
        @value += 1
        @value = @range[0] if @value > @range[1]
      elsif mx < @image_x + @image_w/3
        @value -= 1
        @value = @range[1] if @value < @range[0]
      end
    when :right
      # hmmm. Do nothing. But maybe add something later.
    end
  end

  def set_value(value)
    @value = value
    @value = @range[0] if @value > @range[1]
    @value = @range[1] if @value < @range[0]
  end

end
